package com.caifu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caifu.mapper.ZcOrderingMapper;
import com.caifu.mapper.ZcOrderingRecordDetailsMapper;
import com.caifu.pojo.ZcOrdering;
import com.caifu.pojo.ZcOrderingRecordDetails;
import com.caifu.pojo.ZcOrderingRecords;
import com.caifu.mapper.ZcOrderingRecordsMapper;
import com.caifu.service.ZcOrderingRecordsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.util.Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * <p>
 * 订餐记录表 服务实现类
 * </p>
 *
 * @author Lyf
 * @since 2020-11-09
 */
@Service
public class ZcOrderingRecordsServiceImpl extends ServiceImpl<ZcOrderingRecordsMapper, ZcOrderingRecords> implements ZcOrderingRecordsService {

    @Autowired
    private ZcOrderingRecordsMapper orderingRecordsMapper;
    @Autowired
    private ZcOrderingRecordDetailsMapper orderingRecordDetailsMapper;
    @Autowired
    private ZcOrderingMapper orderingMapper;

    @Override
    @Transactional
    public Map<String, String> getOrgInfo(Long orgId) {
        return orderingRecordsMapper.getOrgInfo(orgId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<JSONObject> saveOrder(String data, String month, String name, String orgId, String supplyFoodAddress,int userNo,String foodType,String reportingStauts,String orderId) {
        try{
            List<JSONObject> result = new ArrayList<>();
            if(StringUtils.isNotBlank(data)){
                Date now = new Date();
                JSONArray arr = JSONArray.fromObject(data);
                if(arr != null && arr.size() > 0){
                    if(StringUtils.isBlank(orderId)) {
                        ZcOrdering order = new ZcOrdering();
                        order.setCreateBy(userNo + "");
                        order.setCreateTime(now);
                        order.setMonth(month);
                        order.setName(name);
                        order.setOrgId(Integer.parseInt(orgId));
                        order.setStatus(reportingStauts);
                        order.setDistributionStatus("1");

                        orderingMapper.insert(order);
                        orderId = order.getId()+"";
                    }else{
                        ZcOrdering o = orderingMapper.selectById(orderId);
                        o.setUpdateBy(userNo+"");
                        o.setUpdateTime(now);
                        orderingMapper.updateById(o);
                    }

                    for(int i = 0 ; i < arr.size() ; i++){
                        JSONObject obj = arr.getJSONObject(i);
                        ZcOrderingRecords or = new ZcOrderingRecords();
                        or.setCost(obj.getString("cost"));
                        or.setType(obj.getString("type"));
                        if("3".equals(or.getType())){
                            or.setAddress(obj.getString("address"));
                        }else{
                            or.setAddress(supplyFoodAddress);
                        }
                        or.setCreateBy(userNo+"");
                        or.setCreateTime(now);
                        or.setDays(obj.getString("days"));
                        or.setDaysCount(obj.getInt("days_count"));
                        or.setDeliveryFee(obj.getString("delivery_fee"));
                        or.setMeals(obj.getString("meals"));
                        or.setMonth(month);
                        or.setStatus("1");
                        or.setSubsidy(obj.getString("subsidy"));
                        or.setOrderId(Long.valueOf(orderId));
                        or.setUserNo(obj.getString("user_no"));
                        or.setUserType(obj.getString("user_type"));
                        or.setFoodType(foodType);
                        orderingRecordsMapper.insert(or);
                        String[] days = or.getDays().split(",");
                        orderingRecordDetailsMapper.delete(new QueryWrapper<ZcOrderingRecordDetails>().eq("record_id",or.getId()));
                        if(days != null && days.length > 0){
                            for(String s : days){
                                ZcOrderingRecordDetails ord = new ZcOrderingRecordDetails();
                                ord.setDay(s);
                                ord.setMonth(or.getMonth());
                                ord.setUserNo(or.getUserNo());
                                ord.setType(or.getFoodType());
                                ord.setFoodType(or.getType());
                                ord.setRecordId(or.getId());
                                ord.setConfirmStatus("1");
                                orderingRecordDetailsMapper.insert(ord);
                            }
                        }
                        obj.put("id",or.getId());
                        obj.put("orderId",orderId);
                        obj.put("isSave","yes");
                        result.add(obj);
                    }
                }
            }
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ZcOrderingRecords saveOrderOne(String data, String month, String name, String orgId, String supplyFoodAddress,int userNo,String foodType,String orderId) {
        try{
            ZcOrderingRecords or = null;
            Date now = new Date();
            if(StringUtils.isNotBlank(data)){
                JSONObject obj = JSONObject.fromObject(data);
                Object idObj = obj.get("id");
                if(idObj != null && StringUtils.isNotBlank(String.valueOf(idObj)) && !"undefined".equals(idObj)){
                    or = orderingRecordsMapper.selectById(String.valueOf(idObj));
                    or.setDays(obj.getString("days"));
                    or.setDaysCount(obj.getInt("days_count"));
                    or.setSubsidy(obj.getString("subsidy"));
                    or.setMeals(obj.getString("meals"));
                    or.setDeliveryFee(obj.getString("delivery_fee"));
                    or.setCost(obj.getString("cost"));
                    or.setType(obj.getString("type"));
                    or.setAddress(obj.getString("address"));
                    or.setUpdateBy(userNo + "");
                    or.setUpdateTime(now);
                    orderingRecordsMapper.updateById(or);
                }else{
                    or = new ZcOrderingRecords();
                    or.setCost(obj.getString("cost"));
                    or.setType(obj.getString("type"));
                    if("3".equals(or.getType())){
                        or.setAddress(obj.getString("address"));
                    }else{
                        or.setAddress(supplyFoodAddress);
                    }
                    or.setCreateBy(userNo+"");
                    or.setCreateTime(now);
                    or.setDays(obj.getString("days"));
                    or.setDaysCount(obj.getInt("days_count"));
                    or.setDeliveryFee(obj.getString("delivery_fee"));
                    or.setMeals(obj.getString("meals"));
                    or.setMonth(month);
                    or.setStatus("1");
                    or.setSubsidy(obj.getString("subsidy"));
                    or.setOrderId(Long.valueOf(orderId));
                    or.setUserNo(obj.getString("user_no"));
                    or.setUserType(obj.getString("user_type"));
                    or.setFoodType(foodType);
                    orderingRecordsMapper.insert(or);
                }
            }
            String[] days = or.getDays().split(",");
            orderingRecordDetailsMapper.delete(new QueryWrapper<ZcOrderingRecordDetails>().eq("record_id",or.getId()));
            if(days != null && days.length > 0){
                for(String s : days){
                    ZcOrderingRecordDetails ord = new ZcOrderingRecordDetails();
                    ord.setDay(s);
                    ord.setMonth(or.getMonth());
                    ord.setUserNo(or.getUserNo());
                    ord.setType(or.getFoodType());
                    ord.setFoodType(or.getType());
                    ord.setRecordId(or.getId());
                    ord.setConfirmStatus("1");
                    orderingRecordDetailsMapper.insert(ord);
                }
            }
            ZcOrdering o = orderingMapper.selectById(or.getOrderId());
            o.setUpdateBy(userNo+"");
            o.setUpdateTime(now);
            orderingMapper.updateById(o);
            return or;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    @Transactional
    public List<Map<String, String>> getOrderData(String orderId, String month, String foodType) {
        return orderingRecordsMapper.getOrderData(orderId,month,foodType);
    }

    @Override
    @Transactional
    public Map<String, Object> getSubsidyStatisticsByUserNo(String userNo) {
        try{
            String[] monthArr = new String[6];
            String[] lunchArr = new String[6];
            String[] supperArr = new String[6];
            Map<String,Object> map = new HashMap<>();
            Date now = new Date();
            for(int i = 6;i >= 1;i--){
                monthArr[6-i] = Util.dateCalculation_month(now,-i,"yyyy-MM");
                Map<String,String> m = orderingRecordDetailsMapper.getSubsidyStatistics(userNo,monthArr[6-i].replace("-",""));
                if(m != null && m.size() > 0){
                    Object obj = m.get("wucan");
                    if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))){
                        lunchArr[6-i] = String.valueOf(obj).substring(0,String.valueOf(obj).indexOf("."));
                    }else{
                        lunchArr[6-i] = "0";
                    }
                    obj = m.get("wancan");
                    if(obj != null && StringUtils.isNotBlank(String.valueOf(obj)) && !"null".equals(String.valueOf(obj))){
                        supperArr[6-i] = String.valueOf(obj).substring(0,String.valueOf(obj).indexOf("."));
                    }else{
                        supperArr[6-i] = "0";
                    }
                }else{
                    lunchArr[6-i] = "0";
                    supperArr[6-i] = "0";
                }
            }
            map.put("month",monthArr);
            map.put("supper",supperArr);
            map.put("lunch",lunchArr);
            return map;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteRecord(String id) {
        try{
            orderingRecordsMapper.delete(new QueryWrapper<ZcOrderingRecords>().eq("id",id));
            orderingRecordDetailsMapper.delete(new QueryWrapper<ZcOrderingRecordDetails>().eq("record_id",id));
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public int getOrderingCount(String orgId, String month, String foodType) {
        return orderingRecordsMapper.getOrderingCount(orgId,month,foodType);
    }

    @Override
    public List<List<String>> getExcelHead(int count) {
        List<List<String>> list = new ArrayList<List<String>>();
        List<String> head0 = new ArrayList<>();
        head0.add("档案编号");

        List<String> head1 = new ArrayList<>();
        head1.add("姓名");

        List<String> head2 = new ArrayList<>();
        head2.add("性别");

        List<String> head3 = new ArrayList<>();
        head3.add("年龄");

        List<String> head122 = new ArrayList<>();
        head122.add("餐别");

        List<String> head4 = new ArrayList<>();
        head4.add("补贴每餐（元）");

        List<String> head5 = new ArrayList<>();
        head5.add("餐费（元）");

        List<String> head6 = new ArrayList<>();
        head6.add("送餐费（元）");

        List<String> head7 = new ArrayList<>();
        head7.add("每客单价（元）");


        list.add(head0);
        list.add(head1);
        list.add(head2);
        list.add(head3);
        list.add(head122);
        list.add(head4);
        list.add(head5);
        list.add(head6);
        list.add(head7);

        //送餐天数
        for (int i = 1; i <= count; i++) {
            List<String> head8 = new ArrayList<>();
            head8.add("送餐(天)");
            head8.add(String.valueOf(i));
            list.add(head8);
        }

        List<String> head9 = new ArrayList<>();
        head9.add("合计（天）");

        List<String> head10 = new ArrayList<>();
        head10.add("补贴金额（元）");

        List<String> head11 = new ArrayList<>();
        head11.add("餐费（元）");

        List<String> head12 = new ArrayList<>();
        head12.add("送餐费（元）");

        List<String> head13 = new ArrayList<>();
        head13.add("实收金额（元）");

        List<String> head14= new ArrayList<>();
        head14.add("送餐方式");

        List<String> head15= new ArrayList<>();
        head15.add("备注");

        list.add(head9);
        list.add(head10);
        list.add(head11);
        list.add(head12);
        list.add(head13);
        list.add(head14);
        list.add(head15);


        return list;


    }

    @Override
    @Transactional
    public List<Map<String, String>> getExportData(String orgId, String month,String type) {
        return orderingRecordsMapper.getExportData(orgId,month,type);
    }

    @Override
    @Transactional
    public List<Map<String,String>> getFoodType(String orgId, String month, String day) {
        return orderingRecordsMapper.getFoodType(orgId,month,day);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirm(String orgId, String month, String type) {
        try{
            Date now = new Date();
            if(StringUtils.isNotBlank(type) && StringUtils.isNotBlank(orgId) && StringUtils.isNotBlank(month)){
                String[] arr = type.split(",");
                String[] dateArr = month.split("-");
                if(arr != null && arr.length > 0){
                    for(String s : arr){
                        orderingRecordsMapper.confirm(orgId,dateArr[0]+dateArr[1],dateArr[2],s,now);
                    }
                    //int count = orderingRecordsMapper.getNoConfirmCount(orgId,dateArr[0]+dateArr[1],dateArr[2]);
                }
            }else{
                throw new Exception("确认失败！");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initData() {
        try{
            List<ZcOrderingRecords> list = orderingRecordsMapper.selectList(new QueryWrapper<ZcOrderingRecords>().orderByAsc("id"));
            if(list != null && list.size() > 0){
                for(ZcOrderingRecords or : list){
                    String[] days = or.getDays().split(",");
                    orderingRecordDetailsMapper.delete(new QueryWrapper<ZcOrderingRecordDetails>().eq("record_id",or.getId()));
                    if(days != null && days.length > 0){
                        System.out.println(days.length);
                        for(String s : days){
                            ZcOrderingRecordDetails ord = new ZcOrderingRecordDetails();
                            ord.setDay(s);
                            ord.setMonth(or.getMonth());
                            ord.setUserNo(or.getUserNo());
                            ord.setType(or.getFoodType());
                            ord.setFoodType(or.getType());
                            ord.setRecordId(or.getId());
                            int i = 1;
                            if(or.getMonth().equals("202012") && s.equals("14")){
                                System.out.println(i++);
                            }
                            ord.setConfirmStatus("1");
                            orderingRecordDetailsMapper.insert(ord);
                        }
                    }
                }
            }
        }catch (Exception e){e.printStackTrace();}
    }
}
